package byx.util.jdbc.core;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author : LukeRen
 * @DateTime: 2022/2/8 16:31
 * @Description :
 * @Version : 1.0.0
 */
public class DataSourceManager {

    private volatile static DataSource instance;
    //锁
    private static Object lock = new Object();

    private DataSourceManager() {

    }

    private static final String JDBC_USER_NAME = "ejar";
    private static final String JDBC_PASSWORD = "Ejar6688!";
    private static final String JDBC_URL = "jdbc:mysql://192.168.5.2:3306/mapcache";

    public static DataSource getDataSource() {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    HikariConfig config = new HikariConfig();
                    config.setJdbcUrl(JDBC_URL);
                    config.setDriverClassName("com.mysql.cj.jdbc.Driver");
                    config.setUsername(JDBC_USER_NAME);
                    config.setPassword(JDBC_PASSWORD);
                    config.addDataSourceProperty("connectionTimeout", "1000"); // 连接超时：1秒
                    config.addDataSourceProperty("idleTimeout", "60000"); // 空闲超时：60秒
                    config.addDataSourceProperty("maximumPoolSize", "10"); // 最大连接数：10
                    config.addDataSourceProperty("autoReconnect", true);
                    config.addDataSourceProperty("serverTimezone", "Asia/Shanghai");
                    config.addDataSourceProperty("useSSL", false); // 禁止使用ssl连接
                    instance = new HikariDataSource(config);
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws SQLException {
        DataSourceManager.getDataSource();

    }

}
